package com.ithaima.service.impl;

import com.ithaima.service.UserService;
import com.ithaima.vo.req.LoginReqVo;
import com.ithaima.vo.resp.LoginRespVo;
import com.ithaima.vo.resp.R;
import com.ithaima.vo.resp.ResponseCode;
import com.itheima.stock.pojo.entity.SysUser;
import com.itheima.stock.pojo.mapper.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import static com.ithaima.vo.resp.ResponseCode.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public SysUser findBayName(String username) {
     return   sysUserMapper.findUserByName(username);
    }

    @Override
    public R<LoginRespVo> loginUser(LoginReqVo vo) {
//        String password = user.getPassword();
//        String username = user.getUsername();
//        String code = user.getCode();
//        if(username ==null||password==null||code  ==null){
//            //
//         return R.error( DATA_ERROR);
//     }
//
//        SysUser userByName = sysUserMapper.findUserByName(username);
//        if(userByName.getUsername()==null){ //该账号不存在
//            return R.error(ACCOUNT_NOT_EXISTS);
//        }
//        boolean matches = passwordEncoder.matches(password, userByName.getPassword());
//
//        if(userByName==null|| matches ){ //用户名或密码错误
//            return R.error(USERNAME_OR_PASSWORD_ERROR);
//        }
//
//        LoginRespVo build = LoginRespVo.builder()
//                .username(userByName.getUsername())
//                .phone(userByName.getPhone())
//                .nickName(userByName.getNickName()).build();
//
//
//        return R.ok(build);



        if (vo==null || StringUtils.isBlank(vo.getUsername()) || StringUtils.isBlank(vo.getPassword())){
            return R.error(ResponseCode.DATA_ERROR);
        }
        //根据用户名查询用户信息
        SysUser user=this.sysUserMapper.findUserByName(vo.getUsername());
        //判断用户是否存在，存在则密码校验比对
        if (user==null || !passwordEncoder.matches(vo.getPassword(),user.getPassword())){
            return R.error(ResponseCode.ACCOUNT_NOT_EXISTS);
        }
        //组装登录成功数据
        LoginRespVo respVo = new LoginRespVo();
        //属性名称与类型必须相同，否则属性值无法copy
        BeanUtils.copyProperties(user,respVo);
        return  R.ok(respVo);
    }
}
